import React, { useEffect, useState } from 'react';
import ReactEcharts from 'echarts-for-react';
import { getRestaurantSalesAPI } from '@/service/restaurant';

const LineChart = () => {
  const [option, setOption] = useState({
    title: {
      text: '月度数据',
    },
    tooltip: {},
    xAxis: {
      data: [],
    },
    yAxis: {},
    series: [
      {
        name: '销量',
        type: 'line',
        data: [],
      },
    ],
  });
  const restaurantId = localStorage.restaurant;

  useEffect(() => {
    getRestaurantSalesAPI(restaurantId).then((data) => {
      let months = Object.keys(data);
      let values = Object.values(data);

      // 创建一个数组，包含月份和对应的值
      let combined = months.map((month, index) => ({
        month,
        value: values[index],
      }));

      // 对数组进行排序
      combined.sort((a, b) => parseInt(a.month) - parseInt(b.month));

      // 分离排序后的月份和值
      months = combined.map((item) => item.month);
      values = combined.map((item) => item.value);

      setOption((prevOption: any) => ({
        ...prevOption,
        xAxis: {
          ...prevOption.xAxis,
          data: months,
        },
        series: [
          {
            ...prevOption.series[0],
            data: values,
          },
        ],
      }));
    });
  }, []);
  return <ReactEcharts option={option} />;
};

export default LineChart;
